package com.gxa.meiye.portal.shop.shopRegister.controller;

import com.gxa.meiye.core.common.ResponseData;
import com.gxa.meiye.core.constant.MassageConstant;
import com.gxa.meiye.core.pojo.shopManagement.Shop;
import com.gxa.meiye.core.utils.QiniuUtils;
import com.gxa.meiye.core.utils.RandomUtils;
import com.gxa.meiye.core.utils.RestUtils;
import com.gxa.meiye.portal.shop.shopRegister.service.RegisterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * @Author cc
 * @PackageName meiye
 * @Package com.gxa.meiye.admin.shop.controller
 * @Date 2022/7/19 11:18
 * @Version 1.0
 */
@RestController
@RequestMapping("shop")
@Api(tags = "注册接口")
@Slf4j
public class PortalRegisterController {
    @Autowired
    private RegisterService registerService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @PostMapping("sendEmail")
    @ApiOperation("发送邮箱验证码")
    public ResponseData sendEmail(String email){
        /*通过远程调用后台查询是否已存在该账号，如果数据库存在该账号，提示邮箱已注册请登录*/
        String url1 = "http://1.117.60.194:8080/shop/checkEmail";
        MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
        params.add("email",email);
        Map map = RestUtils.postWithParams(url1, params);
        Object data = map.get("data");
        ResponseData rd = new ResponseData();
        if (data==null){
            String code = RandomUtils.getSixBitRandom();//获取六位有效数字
            registerService.send(email,code);
            /*向redis中存储邮箱和验证码*/
            ValueOperations<String, String> emailAndCode= redisTemplate.opsForValue();
            emailAndCode.set(email,code,5, TimeUnit.MINUTES);
            rd.setCode(200);
            rd.setMsg("邮箱验证码发送成功");
        }else {
            rd.setMsg("该邮箱账号已注册请登录");
        }

        return rd;
    }


    @PostMapping("registerButton")
    @ApiOperation("点击注册")
    public ResponseData registerButton(MultipartFile imagFile1,MultipartFile imgFile2,  Shop shop){
        String email = shop.getEmail();
        String code = shop.getEmailCode();
        ResponseData rd = new ResponseData();

        Boolean hasKey = redisTemplate.hasKey(email);
        if(code.equals("")||code.equals(null)){
            rd.setMsg("请先获取验证码");
        }else if(!hasKey){
            rd.setMsg("验证码已失效");
        } else if(!(redisTemplate.opsForValue().get(email).equals(code))){
            rd.setMsg("验证码错误");
        }else if(shop.getPwd().equals("")||shop.getPwd().equals(null)){
            rd.setMsg("密码不能为空");
        }else if(!(shop.getPwd().equals(shop.getRepeatPwd()))) {
            rd.setMsg("两次输入的密码不一致");
        }else {
            /*通过远程调用保存到后台数据库*/
            try{
                //1.获取原始第一个文件名
                String originalFilename1 = imagFile1.getOriginalFilename();
                //2.生成新的文件名称
                int index1 = originalFilename1.lastIndexOf(".");//djx.jpg
                String suffix1 = originalFilename1.substring(index1);//.jpg
                String filename1 = UUID.randomUUID().toString() + suffix1;
                //3.调用工具类，上传图片到七牛云
                QiniuUtils.upload2Qiniu(imagFile1.getBytes(), filename1);
                shop.setBusinessLicense(filename1);
                //1.获取原始第二个文件名
                String originalFilename2 = imgFile2.getOriginalFilename();
                //2.生成新的文件名称
                int index2 = originalFilename2.lastIndexOf(".");//djx.jpg
                String suffix2 = originalFilename2.substring(index2);//.jpg
                String filename2 = UUID.randomUUID().toString() + suffix2;
                //3.调用工具类，上传图片到七牛云
                QiniuUtils.upload2Qiniu(imgFile2.getBytes(), filename2);
                //4.返回结果
                shop.setStorePhotos(filename2);

            }catch (Exception e) {
                e.printStackTrace();
                rd.setMsg(MassageConstant.PIC_UPLOAD_FAIL);
            }

            String url2 = "http://1.117.60.194:8080/shop/saveAll";
            MultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
            params.add("name",shop.getName());
            params.add("bank",shop.getBank());
            params.add("pwd",shop.getPwd());
            params.add("bankLocation",shop.getBankLocation());
            params.add("email",shop.getEmail());
            params.add("bankAccount",shop.getBankAccount());
            params.add("businessLicense",shop.getBusinessLicense());
            params.add("longitude",shop.getLongitude());
            params.add("responsiblePerson",shop.getResponsiblePerson());
            params.add("responsiblePersonPhone",shop.getResponsiblePersonPhone());
            params.add("storePhotos",shop.getStorePhotos());
            params.add("telephone",shop.getTelephone());
            params.add("introduction",shop.getIntroduction());
            params.add("location",shop.getLocation());
            RestUtils.postWithParams(url2, params);
            rd.setMsg("账号信息完成");
            rd.setCode(200);
            redisTemplate.delete(email);
        }
            return rd;
    }


}
